<template>
	<div>
		<div class="admin-container" :class="{ 'sidebar-collapsed': isSidebarCollapsed }">
			<!-- 侧边栏 -->
			<div class="sidebar" :class="{ collapsed: isSidebarCollapsed }">
				<div class="sidebar-header">
					<div class="header-content">
						<h3 v-show="!isSidebarCollapsed">后台管理系统</h3>
						<button class="collapse-btn" @click="toggleSidebar"
							:title="isSidebarCollapsed ? '展开侧边栏' : '收缩侧边栏'">
							<svg viewBox="0 0 24 24" fill="currentColor" class="collapse-icon">
								<path v-if="!isSidebarCollapsed" d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z" />
								<path v-else d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z" />
							</svg>
						</button>
					</div>
				</div>
				<el-menu :default-active="activeMenu" class="sidebar-menu" @select="handleMenuSelect"
					:collapse="isSidebarCollapsed">
					<el-menu-item index="dashboard">
						<el-icon>
							<DataBoard />
						</el-icon>
						<span>数据概览</span>
					</el-menu-item>
					<el-menu-item index="users">
						<el-icon>
							<User />
						</el-icon>
						<span>用户管理</span>
					</el-menu-item>
					<el-menu-item index="media">
						<el-icon>
							<Picture />
						</el-icon>
						<span>媒体记录</span>
					</el-menu-item>
					<el-menu-item index="points">
						<el-icon>
							<Coin />
						</el-icon>
						<span>积分明细</span>
					</el-menu-item>
					<el-menu-item index="checkin-records">
						<el-icon>
							<Calendar />
						</el-icon>
						<span>签到记录</span>
					</el-menu-item>
					<el-menu-item index="user-usage">
						<el-icon>
							<Document />
						</el-icon>
						<span>用户使用记录</span>
					</el-menu-item>
					<el-menu-item index="recharge-packages">
						<el-icon>
							<Coin />
						</el-icon>
						<span>充值套餐</span>
					</el-menu-item>
					<el-menu-item index="video-parse-records">
						<el-icon>
							<VideoPlay />
						</el-icon>
						<span>视频解析记录</span>
					</el-menu-item>
				</el-menu>
				<div class="sidebar-footer">
					<el-button type="danger" @click="handleLogout" size="small"
						:class="{ 'collapsed-btn': isSidebarCollapsed }" :title="isSidebarCollapsed ? '退出登录' : ''">
						<span v-show="!isSidebarCollapsed">退出登录</span>
						<svg v-show="isSidebarCollapsed" viewBox="0 0 24 24" fill="currentColor" class="logout-icon">
							<path
								d="M17 7l-1.41 1.41L18.17 11H8v2h10.17l-2.58 2.58L17 17l5-5zM4 5h8V3H4c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h8v-2H4V5z" />
						</svg>
					</el-button>
				</div>
			</div>

			<!-- 主内容区 -->
			<div class="main-content">
				<div class="content-header">
					<h2>{{ pageTitle }}</h2>
					<div class="user-info">
						<span>欢迎，{{ currentUser.username }}</span>
					</div>
				</div>

				<div class="content-body">
					<!-- 数据概览 -->
					<div v-if="activeMenu === 'dashboard'" class="dashboard">
						<el-row :gutter="20">
							<el-col :span="6">
								<el-card>
									<div class="stat-card">
										<div class="stat-number">{{ userCount }}</div>
										<div class="stat-label">用户总数</div>
									</div>
								</el-card>
							</el-col>

							<!-- 添加当日活跃用户卡片 -->
							<el-col :span="6">
								<el-card>
									<div class="stat-card">
										<div class="stat-number">{{ todayUsers }}</div>
										<div class="stat-label">当日活跃用户</div>
									</div>
								</el-card>
							</el-col>
							<!-- 修改月活跃用户卡片 -->
							<el-col :span="6">
								<el-card @click.native="showCalendar" style="cursor: pointer">
									<div class="stat-card">
										<div class="stat-number">{{ monthUsers }}</div>
										<div class="stat-label">月活跃用户</div>
										<div v-if="dailyUsers > 0" class="daily-users">
											已选日期: {{ formatDate(selectedDate) }} -
											{{ dailyUsers }}人
										</div>
									</div>
								</el-card>
							</el-col>
						</el-row>
					</div>

					<!-- 修改后的日历对话框 -->
					<el-dialog v-model="calendarVisible" title="选择查询日期" width="380px" class="calendar-dialog"
						:before-close="handleCalendarClose">
						<div class="calendar-container" v-if="calendarVisible">
							<el-calendar v-model="selectedDate" @change="handleDateSelect" class="custom-calendar">
								<template #header="{ date }">
									<div class="calendar-header">
										<span>{{ formatCalendarTitle(date) }}</span>
									</div>
								</template>
							</el-calendar>
						</div>

						<template #footer>
							<div class="dialog-footer">
								<el-button @click="calendarVisible = false">取消</el-button>
								<el-button type="primary" @click="handleDateSelect(selectedDate)"
									:disabled="!selectedDate">
									查询
								</el-button>
							</div>
						</template>
					</el-dialog>
					<!-- 用户列表对话框 -->
					<el-dialog v-model="showDailyList" :title="`${formatDate(selectedDate)} 活跃用户 (${dailyUsers}人)`"
						width="70%" class="user-list-dialog">
						<el-table :data="dailyUserList" border style="width: 100%" height="500" v-loading="loading">
							<el-table-column prop="id" label="用户ID" width="100" align="center" />
							<el-table-column prop="user_id" label="userid" width="180" />
							<el-table-column prop="openid" label="openid" width="300" />
							<el-table-column prop="nickname" label="用户名" width="120" />
						</el-table>

						<template #footer>
							<div class="dialog-footer">
								<el-button @click="closeUserList">关闭</el-button>
							</div>
						</template>
					</el-dialog>
					<!-- 用户管理 -->
					<div v-if="activeMenu === 'users'" class="users-section">
						<UserManagement :userlist="userlist" @update-user-list="getUserlist" />
					</div>

					<!-- 媒体记录 -->
					<div v-if="activeMenu === 'media'" class="media-section">
						<MediaManagement :media-list="mediaList" @update-media-list="getMediaList" />
					</div>
					<!-- 积分明细 -->
					<div v-if="activeMenu === 'points'" class="points-section">
						<PointDetails />
					</div>
					<!-- 签到记录 -->
					<div v-if="activeMenu === 'checkin-records'" class="checkin-section">
						<CheckinRecordsList />
					</div>
					<!-- 用户使用记录 -->
					<div v-if="activeMenu === 'user-usage'" class="user-usage-section">
						<UserUsageManagement :userlist="userlist" @update-user-list="getUserlist" />
					</div>
					<!-- 套餐充值 -->
					<div v-if="activeMenu === 'recharge-packages'" class="recharge-packages-section">
						<RechargePackages :packages="rechargePackages" @refresh="getRechargePackages" />
					</div>
					<!-- 视频解析记录 -->
					<div v-if="activeMenu === 'video-parse-records'" class="video-parse-records-section">
						<VideoParseRecords />
					</div>
				</div>
			</div>
		</div>
	</div>
</template>

<script setup>
	import {
		ref,
		computed,
		onMounted
	} from "vue";
	import {
		ElMessage,
		ElMessageBox
	} from "element-plus";
	import {
		DataBoard,
		User,
		Picture,
		Upload,
		UploadFilled,
		Document,
		Calendar,
	} from "@element-plus/icons-vue";
	import UserManagement from "./UserManagement.vue";
	import MediaManagement from "./MediaManagement.vue";
	import CheckinRecordsList from "./CheckinRecordsList.vue";
	import PointDetails from "./PointDetails.vue";
	import RechargeRecords from "./RechargeRecords.vue";
	import UserUsageRecords from "./UserUsageRecords.vue";
	import UserUsageManagement from "./UserUsageManagement.vue";
	import usersapi from "../api/usersapi";
	import contents from "../api/contents.js";
	import RechargePackages from "./RechargePackages.vue";
	import rechargeApi from "../api/rechargeApi.js";
	import VideoParseRecords from "./VideoParseRecords.vue"
	import checkinRecordsApi from "../api/checkinRecordsApi.js";
	const emit = defineEmits(["logout"]);
	const userlist = ref([]);
	const mediaList = ref([]);
	const activeMenu = ref("dashboard");
	const currentUser = ref({});
	const isSidebarCollapsed = ref(false);
	const calendarVisible = ref(false);
	const selectedDate = ref(new Date());
	const dailyUsers = ref(0);
	const rechargePackages = ref([]);
	const checkinRecordsList = ref([]);


	// 添加获取充值套餐的方法
	const getRechargePackages = () => {
		rechargeApi.getPackages().then((res) => {
			rechargePackages.value = res.data;
		}).catch(err => {
			ElMessage.error("获取充值套餐失败: " + err.message);
		});
	};

	// 获取签到记录列表
	const getCheckinRecordsList = () => {
		checkinRecordsApi.getcheckinRecordslist().then((res) => {
			checkinRecordsList.value = res.data;
		}).catch(err => {
			ElMessage.error("获取签到记录失败: " + err.message);
		});
	};


	const todayUsers = ref(0); // 日活
	const monthUsers = ref(0); // 月活

	const pageTitle = computed(() => {
		const titles = {
			dashboard: "数据概览",
			users: "用户管理",
			media: "媒体记录",
			points: "积分明细",
			"checkin-records": "签到记录",
			"user-usage": "用户使用记录",
			"recharge-packages": "充值套餐",
			"video-parse-records": "视频解析记录"
		};
		return titles[activeMenu.value];
	});

	const userCount = computed(() => userlist.value.length);
	const mediaCount = computed(() => mediaList.value.length);
	const imageCount = computed(
		() => mediaList.value.filter((item) => item.type === "image").length
	);
	const videoCount = computed(
		() => mediaList.value.filter((item) => item.type === "video").length
	);

	// 新增响应式变量
	const loading = ref(false);
	const dailyUserList = ref([]);
	const showDailyList = ref(false);

	// 格式化日期时间
	const formatDateTime = (datetime) => {
		if (!datetime) return "";
		return new Date(datetime).toLocaleString();
	};

	// 查看用户详情
	const viewUserDetail = (user) => {
		// 这里可以跳转到用户详情页或弹出详情对话框
		console.log("查看用户详情:", user);
		ElMessage.info(`查看用户 ${user.username} 的详情`);
	};
	const closeUserList = () => {
		showDailyList.value = false;
	};
	const handleCalendarClose = () => {
		calendarVisible.value = false;
	};

	const formatCalendarTitle = (date) => {
		try {
			const dateObj = date instanceof Date ? date : new Date(date);
			if (isNaN(dateObj.getTime())) {
				return '选择日期';
			}
			const year = dateObj.getFullYear();
			const month = dateObj.getMonth() + 1;
			return `${year}年${month}月`;
		} catch (e) {
			console.error('日期格式化错误:', e);
			return '选择日期';
		}
	};


	const handleMenuSelect = (index) => {
		activeMenu.value = index;
		// 根据选择的菜单项加载相应数据
		switch (index) {
			case 'checkin-records':
				getCheckinRecordsList();
				break;
			case 'recharge-packages':
				getRechargePackages();
				break;
			default:
				break;
		}
	};


	// 侧边栏收缩功能
	const toggleSidebar = () => {
		isSidebarCollapsed.value = !isSidebarCollapsed.value;
		// 保存状态到localStorage
		localStorage.setItem("sidebarCollapsed", isSidebarCollapsed.value.toString());
	};

	// 新增方法 - 打开日历
	const showCalendar = () => {
		calendarVisible.value = true;
	};

	// 新增方法 - 选择日期后查询
	const handleDateSelect = async (date) => {
		try {
			// 确保date是有效的Date对象
			const dateObj = date instanceof Date ? date : new Date(date);
			if (isNaN(dateObj.getTime())) {
				throw new Error('无效的日期');
			}

			selectedDate.value = dateObj;
			calendarVisible.value = false;
			loading.value = true;

			// 查询当日用户数
			const countResponse = await usersapi.getDailyUsers(dateObj);
			dailyUsers.value = countResponse.data.count;

			// 查询当日用户列表
			const listResponse = await usersapi.getDailyUserList(dateObj);

			dailyUserList.value = listResponse.data;
			console.log('用户列表数据:', dailyUserList.value); // 添加调试日志
			showDailyList.value = true;

			ElMessage.success(`已查询 ${formatDate(dateObj)} 的用户数据`);
		} catch (error) {
			ElMessage.error("查询失败: " + error.message);
		} finally {
			loading.value = false;
		}
	};

	// 辅助方法 - 格式化日期
	const formatDate = (date) => {
		return date.toISOString().split("T")[0];
	};

	// 用户列表
	const getUserlist = () => {
		usersapi.getUserlist().then((res) => {
			userlist.value = res.data;
		});
	};

	// 媒体查询
	const getMediaList = () => {
		contents.getContentslist().then((res) => {
			console.log(res.data);
			mediaList.value = res.data;
		});
	};

	const handleLogout = () => {
		ElMessageBox.confirm("确定要退出登录吗？", "提示", {
			confirmButtonText: "确定",
			cancelButtonText: "取消",
			type: "warning",
		}).then(() => {
			localStorage.removeItem("user");
			emit("logout");
			ElMessage.success("已退出登录");
		});
	};

	const handleUpload = ({
		file
	}) => {
		// 模拟上传
		const newMedia = {
			id: Date.now(),
			name: file.name,
			type: file.type.startsWith("image/") ? "image" : "video",
			url: URL.createObjectURL(file),
			size: (file.size / 1024 / 1024).toFixed(2) + "MB",
			uploadUser: currentUser.value.username,
			uploadTime: new Date().toLocaleDateString(),
		};
		mediaList.value.unshift(newMedia);
		ElMessage.success("上传成功");
	};

	onMounted(() => {
		usersapi.getUserCount().then((res) => {
			console.log(res.data);
			todayUsers.value = res.data.todayUsers;
			monthUsers.value = res.data.monthUsers;
		});

		const userStr = localStorage.getItem("user");
		if (userStr) {
			currentUser.value = JSON.parse(userStr);
		}

		// 恢复侧边栏状态
		const savedCollapsed = localStorage.getItem("sidebarCollapsed");
		if (savedCollapsed !== null) {
			isSidebarCollapsed.value = savedCollapsed === "true";
		}

		getUserlist();
		getMediaList();
		getRechargePackages();
	});
</script>

<style scoped>
	@import "../css/adminPanel.css";

	.points-section {
		padding: 20px;
		background: #fff;
		border-radius: 8px;
		box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
	}

	.user-usage-section {
		padding: 20px;
		background: #fff;
		border-radius: 8px;
		box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
	}

	.recharge-packages-section {
		padding: 20px;
		background: #fff;
		border-radius: 8px;
		box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
	}

	/* 侧边栏收缩相关样式 */
	.sidebar {
		transition: width 0.3s ease;
	}

	.sidebar.collapsed {
		width: 64px !important;
	}

	.sidebar.collapsed .sidebar-header {
		padding: 20px 12px !important;
	}

	.sidebar.collapsed .sidebar-header h3 {
		display: none;
	}

	.header-content {
		display: flex;
		align-items: center;
		justify-content: space-between;
		width: 100%;
	}

	.collapse-btn {
		background: none;
		border: none;
		color: #1976d2;
		cursor: pointer;
		padding: 8px;
		border-radius: 8px;
		transition: all 0.3s ease;
		display: flex;
		align-items: center;
		justify-content: center;
		min-width: 32px;
		height: 32px;
	}

	.collapse-btn:hover {
		background: rgba(25, 118, 210, 0.1);
		transform: scale(1.1);
	}

	.collapse-icon {
		width: 20px;
		height: 20px;
		transition: transform 0.3s ease;
	}

	.sidebar.collapsed .collapse-icon {
		transform: rotate(180deg);
	}

	.sidebar.collapsed .sidebar-menu {
		padding-top: 10px;
	}

	.sidebar.collapsed .sidebar-menu .el-menu-item {
		margin: 6px 8px !important;
		padding: 0 8px !important;
		justify-content: center;
	}

	.sidebar.collapsed .sidebar-menu .el-menu-item span {
		display: none;
	}

	.sidebar.collapsed .sidebar-footer {
		padding: 16px 8px !important;
	}

	.collapsed-btn {
		width: 100% !important;
		padding: 8px !important;
		min-width: 48px !important;
		height: 48px !important;
		display: flex !important;
		align-items: center !important;
		justify-content: center !important;
	}

	.logout-icon {
		width: 20px;
		height: 20px;
	}

	/* 主内容区域适配 */
	.admin-container.sidebar-collapsed .main-content {
		margin-left: 64px;
		transition: margin-left 0.3s ease;
	}

	/* 响应式设计 */
	@media (max-width: 900px) {
		.sidebar.collapsed {
			width: 100vw !important;
			height: 70px !important;
		}

		.admin-container.sidebar-collapsed .main-content {
			margin-left: 0;
			height: calc(100vh - 70px);
		}

		.sidebar.collapsed .sidebar-menu {
			flex-direction: row !important;
			display: flex !important;
			width: 100vw !important;
			padding: 0 !important;
		}

		.sidebar.collapsed .sidebar-menu .el-menu-item {
			margin: 0 8px !important;
			padding: 0 12px !important;
		}

		.sidebar.collapsed .sidebar-menu .el-menu-item span {
			display: block !important;
		}
	}

	/* 新增样式 */
	.stat-card {
		position: relative;
		text-align: center;
		padding: 20px;
	}

	.stat-number {
		font-size: 24px;
		font-weight: bold;
		margin-bottom: 8px;
	}

	.stat-label {
		color: #666;
		font-size: 14px;
	}

	.daily-users {
		margin-top: 10px;
		font-size: 12px;
		color: #888;
		border-top: 1px dashed #eee;
		padding-top: 8px;
	}

	/* 卡片悬停效果 */
	.el-card:hover {
		box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.2);
		transform: translateY(-2px);
		transition: all 0.3s ease;
	}

	/* 用户列表对话框样式 */
	.user-list-dialog {
		border-radius: 8px;
	}

	.user-list-dialog .el-dialog__header {
		border-bottom: 1px solid var(--el-border-color-light);
		margin-right: 0;
	}

	.user-list-dialog .el-dialog__body {
		padding: 20px;
	}

	/* 日历对话框样式 */
	.calendar-dialog {
		border-radius: 8px;
		overflow: hidden;
	}

	.calendar-container {
		padding: 0 10px;
	}

	.custom-calendar {
		--el-calendar-cell-width: 40px;
		--el-calendar-cell-height: 40px;
	}

	.calendar-header {
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 16px;
		font-weight: 500;
		color: var(--el-color-primary);
		padding: 8px 0;
	}

	/* 日历单元格样式 */
	:deep(.el-calendar-table td) {
		border: none;
	}

	:deep(.el-calendar-table .el-calendar-day) {
		height: 100%;
		display: flex;
		justify-content: center;
		align-items: center;
		border-radius: 50%;
		transition: all 0.2s;
	}

	:deep(.el-calendar-table .el-calendar-day:hover) {
		background-color: var(--el-color-primary-light-9);
	}

	:deep(.el-calendar-table .is-selected .el-calendar-day) {
		background-color: var(--el-color-primary);
		color: white;
	}

	/* 对话框底部按钮 */
	.dialog-footer {
		display: flex;
		justify-content: flex-end;
		padding: 10px 20px;
	}

	/* 日期标题格式 */
	.calendar-title {
		font-size: 18px;
		font-weight: 500;
		color: var(--el-text-color-primary);
	}
</style>